#exts文件存在的目的是解决循环引用的目的
#放置拓展文件
import dataclasses
import decimal
import typing
import uuid
from datetime import datetime

from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail
from flask_cors import CORS

from server.resource.util.Serializable import Serializable

db = SQLAlchemy()
mail = Mail()
cors = CORS()


def config_app(app, test_config=None):
    app.config.from_mapping(
        SECRET_KEY='dev',
        # DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

    def default(o: typing.Any) -> typing.Any:
        """
        自定义default方法
        """
        if isinstance(o, Serializable):
            return dict(o)

        if isinstance(o, datetime.datetime):
            return datetime.datetime.strftime(o, "%Y-%m-%d %H:%M:%S")

        if isinstance(o, datetime.date):
            return datetime.date.strftime(o, '%Y-%m-%d')

        if isinstance(o, (decimal.Decimal, uuid.UUID)):
            return str(o)

        if dataclasses and dataclasses.is_dataclass(o):
            return dataclasses.asdict(o)

        if hasattr(o, "__html__"):
            return str(o.__html__())

        raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")

    app.json.default = default  # 指定为自定义的default方法
    app.json.ensure_ascii = False
    app.json.sort_keys = False
    app.json.compact = True

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py')
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)
